import Koa from "koa";
import log4js from "log4js";
import { getClientIpAddress } from "../utils/util";

log4js.configure({
  pm2: true,

  appenders: {
    // 指定日志的输出
    everything: {
      type: "dateFile",
      filename: __dirname + "/logs/all-the-logs.log",
      maxLogSize: "10M", // 单个日志文件最大10M
      backups: 20, // 最多备份20个
    },
  },

  categories: {
    default: { appenders: ["everything"], level: "debug" },
  },
});

export const logger = log4js.getLogger();

export const loggerMiddleware = async (ctx: Koa.Context, next: Koa.Next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  const clientAddress = getClientIpAddress(ctx);
  const logText = `${ctx.method} ${ctx.status} ${
    ctx.url
  } 请求参数： ${JSON.stringify(ctx.request.body)} 响应参数： ${JSON.stringify(
    ctx.body
  )} - ${clientAddress} - ${ms}ms`;

  logger.info(logText);
};
